package com.eunion.fileserver.upload;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eunion.fileserver.ftp.FtpHelper;

/**
 * 文件上传变量定义，单例模式,初始化加载.同时提供一些快捷的helper工具类.
 * @since 2017年2月17日
 */
public final class FileUploadHelper {

	static Logger LOG = LoggerFactory.getLogger(FileUploadHelper.class);

	private static final FileUploadHelper instance = new FileUploadHelper();//饿汉单例 

	private static ResourceBundle RESOURCE = null;

	/**
	 * 私有构建方法，初始化获取变量.
	 */
	private FileUploadHelper() {
		RESOURCE = ResourceBundle.getBundle("fileserver");
		//有配置文件，且配置的ftp和本地的文件系统 
		if (RESOURCE != null && RESOURCE.getString("ftp.use") != null) {
			String os = System.getProperty("os.name").toLowerCase();
			LOG.info("System name is ： {}", os);
			if (null == RESOURCE.getString("ftp.use")) {
				this.ftpUse = null;
				LOG.info("System is not config fileserver");
				return;
			}

			this.ftpUse = RESOURCE.getString("ftp.use").equals("true") ? Boolean.TRUE : Boolean.FALSE;
			this.imageCompress = RESOURCE.getString("file.image.compress").equals("true") ? Boolean.TRUE : Boolean.FALSE;

			LOG.info("upload.use.ftp ： {}", this.ftpUse);
			if (null != this.ftpUse) {
				if (this.ftpUse) {
					this.ftpHost = RESOURCE.getString("ftp.host");//=localhost
					this.ftpPort = Integer.valueOf(RESOURCE.getString("ftp.port"));//=21
					this.ftpUser = RESOURCE.getString("ftp.user");//=ken123
					this.ftpPwd = RESOURCE.getString("ftp.pwd");//=123456

				} else {
					if (os.contains("windows")) {
						this.uploadLocalPath = RESOURCE.getString("upload.path.local.windows");//文件上传路径
					} else {
						this.uploadLocalPath = RESOURCE.getString("upload.path.local.linux");//文件上传路径
					}
					LOG.warn("please config Context Path in server.xml,windows:{},linux:{} for localUploadFilePath:{}", "<Context docBase=\"C:/fileserver/\" path=\"/files\" reloadable=\"false\"/>",
					    "<Context docBase=\"/home/fileserver/\" path=\"/files\" reloadable=\"false\"/>", this.uploadLocalPath);
					//如果配置不使用FTP就要创建本地目录TODO 
					File fileCheckDir = new File(this.uploadLocalPath);
					if (fileCheckDir.exists() && fileCheckDir.isDirectory()) {
						LOG.info("upload.path exist ： {}", this.uploadLocalPath);
					} else {
						boolean flag = fileCheckDir.mkdirs();
						if (flag) {
							LOG.info("upload.path {} not exist , create OK", this.uploadLocalPath);
						} else {
							LOG.error("upload.path {} not exist , create error , please check authorities of the director", this.uploadLocalPath);
						}
					}
				}
				this.fileServerUrl = RESOURCE.getString("file.server.url");//项目根路径

				if (!this.fileServerUrl.endsWith("/")) {
					this.fileServerUrl = this.fileServerUrl + "/";
				}

				this.fileType = RESOURCE.getString("upload.type");
				LOG.info("file.server.url ： {}", this.fileServerUrl);
			}
		}
	}

	/**
	 * 获取本实例.
	 */
	public static FileUploadHelper getInstance() {
		return instance;
	}

	/**最大文件上传大小*/
	public static int MAX_FILESIZE = 20 * 1024 * 1024;

	/**最大内存中大小*/
	public static int MAX_MEM_SIZE = 4 * 1024;

	/**根目录常量定义，/*/
	public static final String ROOT_PATH = "/";

	/**默认目录*/
	public static final String DEFAULT_UPLOAD_DIR = "upload/";

	/**字符串编码格式常量定义，UTF8.*/
	public static final String CHAR_UTF8 = "UTF-8";

	/**Ftp 配置 是否使用ftp*/
	private Boolean ftpUse;

	/**图片压缩开关*/
	private boolean imageCompress;

	/** 文件上传路径 区分windows和linux */
	private String uploadLocalPath;

	/**图片访问路径，HTTP*/
	private String fileServerUrl;

	/**Ftp 配置 host*/
	private String ftpHost;

	/**Ftp 配置 user*/
	private String ftpUser;

	/**Ftp 配置 pwd*/
	private String ftpPwd;

	/**Ftp 配置 port*/
	private Integer ftpPort;

	/**可上传文件类型*/
	private String fileType;

	/**
	 * 获取配置文件的ResourceBundle，以便用来查找额外的配置量.
	 */
	public static ResourceBundle getRESOURCE() {
		return RESOURCE;
	}

	/**
	 * 是否使用ftp
	 */
	public Boolean isFtpUse() {
		return ftpUse;
	}

	/**
	 * 本地上传的root地址，用于非ftp的场景.
	 */
	public String getUploadLocalPath() {
		return uploadLocalPath;
	}

	/**
	 * 文件服务器访问的根域名或webContext.
	 */
	public String getFileServerUrl() {
		return fileServerUrl;
	}

	/**
	 * ftp ip.
	 */
	public String getFtpHost() {
		return ftpHost;
	}

	/**
	 * ftp 用户.
	 */
	public String getFtpUser() {
		return ftpUser;
	}

	/**
	 * ftp 密码.
	 */
	public String getFtpPwd() {
		return ftpPwd;
	}

	/**
	 * ftp 端口.
	 */
	public Integer getFtpPort() {
		return ftpPort;
	}

	/**
	 * 文件上传允许的类型.
	 */
	public String getFileType() {
		return fileType;
	}

	/**
	 * 获取ftp对象,内部创建FtpHelper(含用户名密码等).
	 */
	public FtpHelper getFtpHelper() {
		return new FtpHelper(this.ftpHost, this.ftpPort, this.ftpUser, this.ftpPwd);
	}

	/**
	 * 返回默认时间格式路径yyyyMM/dd/ 
	 */
	public static String getSubTimeFolder() {
		DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT);
		return df.format(new Date());
	}

	/**
	 * 获取UUID随机码.
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * Java文件操作 获取文件扩展名 .
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * 获取系统临时目录java.io.tmpdir.
	 * @return
	 */
	public static final String getTmpDir() {
		return System.getProperty("java.io.tmpdir");
	}

	/**
	 * 是否配置了图片压缩功能.
	 */
	public boolean getImageCompress() {
		return imageCompress;
	}

	/** ~~~ 系统默认建立和使用的以时间字符串作为文件名称的时间格式*/
	private static final String DEFAULT_SUB_FOLDER_FORMAT = "yyyy/MM/dd/";
}
